package com.yashi.springmvcjbpm.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.jbpm.api.history.HistoryProcessInstance;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yashi.springmvcjbpm.util.GetConnection;
import com.yashi.springmvcjbpm.util.JBPMUtil;

@Controller
public class ProcessInstanceController {
	private JBPMUtil jbpmUtil = new JBPMUtil();
	@RequestMapping("/showProcess")
	public String showProcess(HttpServletRequest request) {
		List<Map<String, Object>> proList = new ArrayList<Map<String, Object>>();
		List<HistoryProcessInstance> processList = jbpmUtil.getAllProIns();
		for(int i=0;i<processList.size();i++) {
			HistoryProcessInstance instance = processList.get(i);
			Map<String, Object> proMap = new HashMap<>();
			proMap.put("processId", instance.getProcessInstanceId());
			proMap.put("assignee", getAssignee(instance.getProcessInstanceId()));
			proMap.put("startTime", instance.getStartTime());
			proMap.put("endTime", instance.getEndTime());
			proMap.put("state", instance.getState());
			proList.add(proMap);
			
		}
		System.out.println(proList);
		request.setAttribute("processList", proList);
		return "processInstance";
		
	}
	private String getAssignee(String processInstanceId) {
		String sql="select *from `leave` where leaveInstanceId='"+processInstanceId+"'";
		GetConnection connection = new GetConnection();
		String staffName = null;
		try {
			Connection con = connection.getCon();
			Statement statement = con.createStatement();
			ResultSet rs = statement.executeQuery(sql);
			while(rs.next()) {
				staffName=rs.getString("staffName");
			}
		} catch (ClassNotFoundException | IOException | SQLException e) {
			
			e.printStackTrace();
		}
		return staffName;
	}
}
